package com.songcha.module_bookreader.ui.activity.reader

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.songcha.module_bookreader.bean.book.BookChapterContentDataBean
import com.songcha.library_base.interfaces.IApiResult
import com.songcha.library_base.interfaces.IResult
import com.songcha.library_base.mvvm.base.BaseViewModel
import com.songcha.library_business.bean.book.BookBean
import com.songcha.library_business.bean.book.BookChapterCatalogBean
import com.songcha.library_business.event.book.InBookShelfEvent
import com.songcha.library_business.manager.TaskManager
import com.songcha.library_business.proxy.database.BookDownloadDaoManager
import com.songcha.library_business.proxy.database.BookLastReadDaoManager
import com.songcha.library_business.proxy.database.BookReadProgressDaoManager
import com.songcha.library_business.proxy.database.BookShelfDaoManager
import com.songcha.library_business.proxy.database.BookTodayReadChapterCountDaoManager
import com.songcha.library_business.proxy.database.BookTodayReadTimeDaoManager
import com.songcha.library_business.proxy.database.TodayObtainGoldCountDaoManager
import com.songcha.library_business.proxy.userinfo.UserInfoManager
import com.songcha.library_common.helper.SharedPreferenceHelper
import com.songcha.library_common.util.TimeUtil
import com.songcha.library_network.bean.BaseBean
import com.songcha.library_network.bean.BaseIntDataBean
import io.reactivex.Observable
import org.greenrobot.eventbus.EventBus

class BookReadViewModel(app: Application):BaseViewModel<BookReadRepository>(app) {
    companion object{
        const val BOOKREAD_FILENAME = "bookreader"

    }

    lateinit var bookBean:BookBean
    var mBgIdx=1
    //var mFlipStyle=1

    var DEFAULT_FONTSIZE = 25

    val fontSize=MutableLiveData(DEFAULT_FONTSIZE)
    val flipStyle=MutableLiveData(1)
    val isDarkMode=MutableLiveData(false)
    val chapterList=MutableLiveData<MutableList<BookChapterCatalogBean.DataBean>>(mutableListOf())
    val chapterListState=MutableLiveData<Boolean>()
    val currentChapter=MutableLiveData(1)
    val lineSpaceRatio=MutableLiveData(2)
    //direct jump chapter from external
    var argChapter=0
    //is download read
    var isFromDownload=false
    @JvmField
    var readProgress = intArrayOf(1,0,0)
    var isInBookShelf=MutableLiveData(false)
    var startReadTime=0L
    var endReadTime=0L

    var chapterContent=MutableLiveData<String>()
    //whether jump to chapter,don't jump when just open,jump when user select or load chapter
    var isJumpTo:Boolean?=null
    //whether jump to end
    var isJumpToEnd:Boolean=false
    //the chapter want to jump
    var jumpToChapter:Int?=null
    //jump progress
    var jumpBeginPos=0
    var jumpEndPos=0

    var chapterContentState=MutableLiveData<Boolean>()

    init {
        startReadTime=TimeUtil.getCurrentTimeSecond()
        endReadTime=TimeUtil.getCurrentTimeSecond()
        getReadBackgroundIdx()
        getDarkMode()
        getFlipStyle()
        getFontSize()
        getLineSpaceRation()
        //getReadProgress()
    }

    fun getBookChapterCatalog(){
        if(isFromDownload){
            handleDataObserver(repository!!.getBookChapterCatalogFromDownload(bookBean.id),object :
                IResult<BookChapterCatalogBean> {
                override fun onSuccess(bean: BookChapterCatalogBean) {
                    if(bean.data.size>0){
                        onLoadSuccess()
                        chapterList.value=bean.data
                        chapterListState.value=true
                    }else{
                        chapterListState.value=false
                    }
                }

                override fun onError(e: Throwable) {
                    chapterListState.value=false
                }

            },true)
        }else{
            handleApiDataObserver(repository!!.getBookChapterCatalog(bookBean.id.toInt()),object :IApiResult<BookChapterCatalogBean>{
                override fun onSuccess(bean: BookChapterCatalogBean) {
                    if(bean.data.size>0){
                        onLoadSuccess()
                        chapterList.value=bean.data
                        chapterListState.value=true
                    }else{
                        chapterListState.value=false
                    }
                }

                override fun onError(e: Throwable) {
                    chapterListState.value=false
                }

            },true)
        }


    }

    fun addBookTodayReadTime():Int{
        return BookTodayReadTimeDaoManager.addTodayReadTime(this.startReadTime,this.endReadTime)
    }

    fun addBookTodayReadChapterCount(endChapter: Int):Int{
        return BookTodayReadChapterCountDaoManager.addTodayReadChapterCount(currentChapter.value!!,endChapter)
    }

    fun addChapter(chapter:String){
        val tmp=chapterList.value
        val bean=BookChapterCatalogBean.DataBean(1,1,1,chapter,1,1,false,"")
        tmp!!.add(bean)
        chapterList.value=tmp!!
    }

    fun setCurrentChapter(curChapter: Int){
        currentChapter.value=curChapter
    }

    fun setReadBackgroundIdx(idx:Int){
        SharedPreferenceHelper.setInt(BOOKREAD_FILENAME,"read_background",idx)
        mBgIdx=idx
    }

    fun getReadBackgroundIdx(){
        var bg=SharedPreferenceHelper.getInt(BOOKREAD_FILENAME,"read_background",1)
        mBgIdx=bg
    }

    fun switchDarkMode(isDark:Boolean){
        SharedPreferenceHelper.setBoolean(BOOKREAD_FILENAME,"is_dark",isDark)
        isDarkMode.value=isDark
    }

    fun getDarkMode(){
        val isDark=SharedPreferenceHelper.getBoolean(BOOKREAD_FILENAME,"is_dark")
        isDarkMode.value=isDark
    }

    fun setFlipStyle(style:Int){
        SharedPreferenceHelper.setInt(BOOKREAD_FILENAME,"flip_style",style)
        flipStyle.value=style
    }

    fun getFlipStyle(){
        var style=SharedPreferenceHelper.getInt(BOOKREAD_FILENAME,"flip_style",1)
        flipStyle.value=style
    }

    fun addFontSize(delta:Int):Boolean{
        if(fontSize.value!!<=14 && delta<0) return false
        if(fontSize.value!!>=32 && delta>0) return false
        fontSize.value=fontSize.value!!+delta
        SharedPreferenceHelper.setInt(BOOKREAD_FILENAME,"font_size",fontSize.value!!)
        return true
    }

    fun setDefaultFontSize(){
        fontSize.value=DEFAULT_FONTSIZE
        SharedPreferenceHelper.setInt(BOOKREAD_FILENAME,"font_size",DEFAULT_FONTSIZE)
    }

    fun getFontSize(){
        fontSize.value=SharedPreferenceHelper.getInt(BOOKREAD_FILENAME,"font_size",DEFAULT_FONTSIZE)
    }

    fun setLineSpaceRatio(ratio:Int){
        if(ratio<2 || ratio>5) return
        lineSpaceRatio.value=ratio
        SharedPreferenceHelper.setInt(BOOKREAD_FILENAME,"line_space_ratio",ratio)
    }

    fun getLineSpaceRation(){
        lineSpaceRatio.value=SharedPreferenceHelper.getInt(BOOKREAD_FILENAME,"line_space_ratio",2)
    }

    fun saveReadProgress(beginPosition:Int,endPosition:Int,chapterSize:Int){
        if(bookBean.id.isBlank()) return
        if(currentChapter.value==null) return
        readProgress= intArrayOf(currentChapter.value!!,beginPosition,endPosition)
        BookReadProgressDaoManager.saveReadProgress(bookBean.id,currentChapter.value!!,beginPosition,endPosition,chapterSize)
    }

    fun getReadProgress(){
        if(bookBean.id.isBlank()) return
        if(argChapter>0){
            readProgress= intArrayOf(argChapter,0,0)
        }else{
            readProgress=BookReadProgressDaoManager.getReadProgress(bookBean.id)
        }
        currentChapter.value=readProgress[0]
    }

    fun getChapterTitleList():MutableList<String>{
        val chapterTitleList= mutableListOf<String>()
        if(chapterList.value==null) return chapterTitleList
        for(item in chapterList.value!!){
            chapterTitleList.add(item.chapterTitle)
        }
        return chapterTitleList
    }

    fun getChapterContent(chapter:Int){
        if(bookBean.isFromSDCard) return
        if(chapterList.value==null) return
        if(chapter==0) return
        if(chapterList.value!!.size<chapter) return
        val chapterId=chapterList.value!![chapter-1].chapterId

        val diskObs=repository!!.getDiskChapterCotent(bookBean.id,chapter)
        val netObs=repository!!.getChapterContent(chapterId)
        val obs=Observable.concat(diskObs,netObs)

        handleApiDataObserver(obs,object :IApiResult<BookChapterContentDataBean>{
            override fun onSuccess(bean: BookChapterContentDataBean) {
                //onLoadSuccess()
               // currentChapter.value=chapter
                if(bean.data==null) return
                //CacheManager.getInstance().saveChapterFile(bookBean.id, chapter, bean.data.content)
                chapterContent.value=bean.data.content
                chapterContentState.value=true
            }

            override fun onError(e: Throwable) {
                chapterContentState.value=false
            }
        })

    }

    fun saveLastRead(){
        if(bookBean.id.isBlank()) return
        BookLastReadDaoManager.saveLastReadBook(bookBean.id)
    }

    fun addBookToShelf(){
        if(BookShelfDaoManager.addToBookShelf(bookBean.id)){
            isInBookShelf.value=true
            EventBus.getDefault().post(InBookShelfEvent(bookBean.id,true))
        }
        if(UserInfoManager.checkLogin()){
            handleApiDataObserver(repository!!.addToBookShelf(bookBean.id.toInt()),object :IApiResult<BaseBean>{
                override fun onSuccess(bean: BaseBean) {

                }
            })
        }
    }

    fun getIsBookInShelf(){
        isInBookShelf.value=BookShelfDaoManager.isInBookShelf(bookBean.id)
    }

    fun hasBookDownloaded():Boolean{
        return BookDownloadDaoManager.hasBookDownloaded(bookBean.id)
    }

    fun completedRewardTask(){
        if(TaskManager.rewardTaskId == 0) return
        handleApiDataObserver(repository.completeTask(TaskManager.rewardTaskId),object :IApiResult<BaseIntDataBean>{
            override fun onSuccess(bean: BaseIntDataBean) {
                TodayObtainGoldCountDaoManager.addTodayObtainGoldCount(bean.data)
            }

            override fun onError(e: Throwable) {

            }

        },false,false,false)


    }


}